﻿using lucky_dog_backend.Models;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace lucky_dog_backend.Services
{
    public class UserService
    {
        private readonly IMongoCollection<User> _users;

        public UserService(ILuckyDogDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);
            _users = database.GetCollection<User>(settings.UsersCollectionName);
        }

        public async Task<List<User>> Get() => await _users.Find(user => true).ToListAsync();
        public async Task<User> GetAccount(string account) => await _users.Find(user => user.Account == account).FirstOrDefaultAsync();
        public async Task<User> Get(string id) =>
            await _users.Find(user => user.Id == id).FirstOrDefaultAsync();
        public async Task<User> Create(User user)
        {
            await _users.InsertOneAsync(user);
            return user;
        }
        public bool IsValid(LoginRequestDTO req)
        {
            var user = _users.Find(user => user.Account == req.Account && user.Password == req.Password).FirstOrDefault();
            return user != null;
        }
    }
}
